package com.pitop.base;

import com.pitop.core.entity.BeanRet;
import com.pitop.t.service.TpermissionSV;
import com.pitop.t.service.TuserSV;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


@Controller
public class LoginController {

    @Autowired
    private TuserSV userService;

    @Autowired
    private TpermissionSV permissionService;

    /**
     * 登录
     *1.创建subject实例
     *2.判断用户是否已登录
     *3.
     * @return 登录信息
     */
    @ApiOperation(value = "登录", notes = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", paramType = "query")
    })
    @PostMapping(value = "/login")
    @ResponseBody
    public BeanRet login(String userName, String password) {
        Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName.trim(), DigestUtils.md5Hex(password).toCharArray());
            token.setRememberMe(true);
            try {
                subject.login(token);
            } catch (UnknownAccountException e) {
                return BeanRet.create(false, "用户名不存在");

            } catch (IncorrectCredentialsException e) {
                return BeanRet.create(false, "密码不正确");
            }
        return BeanRet.create(true, "登录成功");
    }

    /**
     * 退出
     *
     * @return 退出
     */
    @ApiOperation(value = "退出", notes = "退出")
    @PostMapping(value = "/logout")
    @ResponseBody
    public BeanRet logout(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BeanRet.create(true, "成功退出");
    }
}
